package com.lottery.im.module.main.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.util.Patterns;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindArray;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.api.result.ApiResult;
import com.lottery.im.api.result.entity.LoginEntity;
import com.lottery.im.api.result.entity.UpdateInfo;
import com.lottery.im.api.result.entity.UserInfo;
import com.lottery.im.api.result.entity.msg_bulletin.MessageCount;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.constant.Constants;
import com.lottery.im.constant.RxBusCode;
import com.lottery.im.constant.SpKeyConstant;
import com.lottery.im.module.chat.ui.ConversationListFragment;
import com.lottery.im.module.chat.ui.CreateGroupFriendFragment;
import com.lottery.im.module.chat.ui.LocalSearchFragment;
import com.lottery.im.module.chat.ui.SearchUserGroupFragment;
import com.lottery.im.module.contact.ui.ContactFragment;
import com.lottery.im.module.main.presenter.HomePresenter;
import com.lottery.im.module.main.view.HomeView;
import com.lottery.im.module.result.ui.AllGameFragment;
import com.lottery.im.module.result.ui.ResultFragment;
import com.lottery.im.module.service.ui.MessageAndBulletinFragment;
import com.lottery.im.module.service.ui.ServiceFragment;
import com.lottery.im.module.setting.ui.ProfileFragment;
import com.lottery.im.module.tim.model.UnreadMessageTip;
import com.lottery.im.pop.MenuFilterPopup;
import com.lottery.im.util.FragmentManagerUtil;
import com.lottery.im.util.MyUtils;
import com.lottery.im.util.RelativePopupWindow;
import com.lottery.im.util.SPUtils;
import com.lottery.im.util.StatusBarHelper;
import com.lottery.im.util.rxbus.RxBus;
import com.lottery.im.util.rxbus.Subscribe;
import com.lottery.im.widget.dialog.CheckUpdateDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import java.util.ArrayList;
import java.util.List;

/*
 * 首页
 * */
public class HomeFragment extends BaseSwipeFragment<HomePresenter> implements HomeView {

  @BindView(R.id.tabs) CommonTabLayout mTabs;
  @BindView(R.id.tv_title) TextView mTvTitle;
  @BindView(R.id.tv_sub_title) TextView mTvSubTitle;
  @BindView(R.id.iv_right1) ImageButton mIvRight1;
  @BindView(R.id.iv_right2) ImageButton mIvRight2;
  @BindView(R.id.layout_title_bar) RelativeLayout mLayoutTitlebar;

  @BindArray(R.array.home_tabs) String[] mTabNames;
  @BindArray(R.array.title_bar_add_menu) String[] mMenuArray;

  @BindString(R.string.chat) String mTitleStr1;
  @BindString(R.string.contact) String mTitleStr2;
  @BindString(R.string.lottery_result) String mTitleStr3;

  private final static int REQUESTCODE=100;

  private int[] mIconArray = {
      R.drawable.icon_tc_cjql, R.drawable.icon_tc_jhy, R.drawable.icon_tc_sys
  };

  private int[] mTabSelectedIconRes =
      {
          R.drawable.nav_chat_checked, R.drawable.nav_contact_checked,
          R.drawable.nav_result_checked,
          R.drawable.nav_service_checked
      };

  private int[] mTabUnselectedIconRes =
      {
          R.drawable.nav_chat_unchecked, R.drawable.nav_contact_unchecked,
          R.drawable.nav_result_unchecked, R.drawable.nav_service_unchecked
      };

  // Fragment 列表
  private ArrayList<Fragment> mFragments;
  // Fragment 管理器
  private FragmentManagerUtil mFragmentManagerUtil;

  private ConversationListFragment mChatFragment;
  private ContactFragment mContactFragment;
  private ResultFragment mResultFragment;
  private ServiceFragment mServiceFragment;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_home;
  }

  @Override protected void initPresenter() {
    presenter = new HomePresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {
    RxBus.get().register(this);
    initTabs();
    initFragments();
    if (MyApplication.getInstance().getUserInfo().getUserType().equals(
        Constants.AGENT_USER_TYPE_NAME)) {
      mIvRight1.setVisibility(View.VISIBLE);
    } else {
      mIvRight1.setVisibility(View.GONE);
    }
    presenter.refreshUserInfo();
  }

  @Override protected void onFragmentResult(int requestCode, int resultCode, Intent data) {
    super.onFragmentResult(requestCode, resultCode, data);
    if(requestCode==REQUESTCODE){
      presenter.queryUserSystemMessageCount();
    }
  }

  @OnClick({ R.id.iv_left1, R.id.iv_right1, R.id.iv_right2 }) public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_left1:
        startFragment(new ProfileFragment());
        break;
      case R.id.iv_right2:
        startFragment(new LocalSearchFragment());
        break;
      case R.id.iv_right1:
        switch (mTabs.getCurrentTab()) {
          case 2:
            startFragment(new AllGameFragment());
            break;
          case 3:
            startFragmentForResult(new MessageAndBulletinFragment(),REQUESTCODE);
            break;
          default:
            showMenu();
            break;
        }
        break;
    }
  }

  /*
   *  初始化 tab
   * */
  private void initTabs() {
    ArrayList<CustomTabEntity> tabEntities = new ArrayList<>();
    for (int i = 0; i < mTabNames.length; i++) {
      final int position = i;
      tabEntities.add(new CustomTabEntity() {
        @Override public String getTabTitle() {
          return mTabNames[position];
        }

        @Override public int getTabSelectedIcon() {
          return mTabSelectedIconRes[position];
        }

        @Override public int getTabUnselectedIcon() {
          return mTabUnselectedIconRes[position];
        }
      });
    }
    mTabs.setTabData(tabEntities);
    mTabs.setOnTabSelectListener(new OnTabSelectListener() {
      @Override public void onTabSelect(int position) {
        mFragmentManagerUtil.setFragments(position);
        changeTitleAndIcon(position);
        SPUtils.put(mActivity, SpKeyConstant.HOME_TAB_KEY, "" + position);
      }

      @Override public void onTabReselect(int position) {

      }
    });
    mTabs.setCurrentTab(0);
    mTvTitle.setText(mTitleStr1);
  }

  /*
   *  初始化 fragment
   * */
  private void initFragments() {
    if (null == mFragments || mFragments.size() == 0) {
      mFragments = new ArrayList<>();
      if (null == mChatFragment) {
        mChatFragment = new ConversationListFragment();
      }
      mFragments.add(mChatFragment);
      if (null == mContactFragment) {
        mContactFragment = new ContactFragment();
      }
      mFragments.add(mContactFragment);
      if (null == mResultFragment) {
        mResultFragment = new ResultFragment();
      }
      mFragments.add(mResultFragment);
      if (null == mServiceFragment) {
        mServiceFragment = new ServiceFragment();
      }
      mFragments.add(mServiceFragment);
      mFragmentManagerUtil =
          new FragmentManagerUtil(getActivity().getSupportFragmentManager(), R.id.home_container,
              mFragments);
    }
  }

  /*
   * 切换tab修改标题+左右图标
   * */
  private void changeTitleAndIcon(int position) {
    if (position == 0) {
      mTvTitle.setText(mTitleStr1);
      if (MyApplication.getInstance()
          .getUserInfo()
          .getUserType()
          .equals(Constants.AGENT_USER_TYPE_NAME)) {
        mIvRight1.setImageResource(R.drawable.icon_title_add);
        mIvRight1.setVisibility(View.VISIBLE);
      } else {
        mIvRight1.setVisibility(View.GONE);
      }
      mIvRight2.setVisibility(View.GONE);
      mTvSubTitle.setVisibility(View.GONE);
    } else if (position == 1) {
      mTvTitle.setText(mTitleStr2);
      if (MyApplication.getInstance()
          .getUserInfo()
          .getUserType()
          .equals(Constants.AGENT_USER_TYPE_NAME)) {
        mIvRight1.setImageResource(R.drawable.icon_title_add);
        mIvRight1.setVisibility(View.VISIBLE);
      } else {
        mIvRight1.setVisibility(View.GONE);
      }
      mIvRight2.setImageResource(R.drawable.icon_title_search);
      mIvRight2.setVisibility(View.VISIBLE);
      mTvSubTitle.setVisibility(View.GONE);
    } else if (position == 2) {
      mTvTitle.setText(mTitleStr3);
      mIvRight1.setImageResource(R.drawable.icon_title_drawer);
      mIvRight1.setVisibility(View.VISIBLE);
      mIvRight2.setVisibility(View.GONE);
      mTvSubTitle.setVisibility(View.GONE);
    } else {
      mTvTitle.setText("");

      presenter.queryUserSystemMessageCount();

      mIvRight1.setVisibility(View.VISIBLE);
      mIvRight2.setVisibility(View.GONE);
      mTvSubTitle.setVisibility(View.VISIBLE);
    }
  }

  /*
   *  点击加号 显示菜单按钮
   * */
  private void showMenu() {
    MenuFilterPopup menuFilterPopup = new MenuFilterPopup(mContext);
    List<MenuFilterPopup.MenuFilterEntity> items = new ArrayList<>();
    for (int i = 0; i < mMenuArray.length; i++) {
      MenuFilterPopup.MenuFilterEntity menuFilterEntity = new MenuFilterPopup.MenuFilterEntity();
      menuFilterEntity.setTitle(mMenuArray[i]);
      menuFilterEntity.setIconRes(mIconArray[i]);
      items.add(menuFilterEntity);
    }
    menuFilterPopup.setDataSelect(items,
        (adapter, view, position) -> {
          switch (position) {
            case 0:
              startFragment(new CreateGroupFriendFragment());
              break;
            case 1:
              startFragment(SearchUserGroupFragment.create(""));
              break;
            case 2:
              new RxPermissions(getActivity()).request(Manifest.permission.CAMERA)
                  .subscribe(new Observer<Boolean>() {
                    @Override public void onSubscribe(Disposable d) {
                    }

                    @Override public void onNext(Boolean aBoolean) {
                      if (aBoolean) {
                        Intent intent = new Intent(mActivity, CaptureActivity.class);
                        startActivityForResult(intent, 888);
                      } else {
                        showToast("你已拒绝访问使用摄像头权限～");
                      }
                    }

                    @Override public void onError(Throwable e) {

                    }

                    @Override public void onComplete() {

                    }
                  });

              break;
          }
        });
    menuFilterPopup.showOnAnchor(mLayoutTitlebar, RelativePopupWindow.VerticalPosition.BELOW,
        RelativePopupWindow.HorizontalPosition.LEFT);
  }

  /**
   * 设置未读tab显示
   */
  @Subscribe(code = RxBusCode.UNREAD_NUM_CODE)
  public void setMsgUnread(UnreadMessageTip tip) {

    int num = tip.getNum();
    if (num > 0) {
      mTabs.showMsg(tip.getPosition(), num);
    } else {
      mTabs.hideMsg(tip.getPosition());
    }
  }

  @Override public void querySuccess(UpdateInfo info) {
    String appVersion = info.getAppVersion();
    String appUpgradeUrl = info.getAppUpgradeUrl();
    String appUpgradeContent = info.getAppUpgradeContent();
    if (MyUtils.compareVersion(getActivity(), appVersion) == -1) {
      CheckUpdateDialog.create(getActivity(), appVersion, appUpgradeUrl, appUpgradeContent);
    }
  }

  @Override public void queryMessageCountResult(ApiResult<MessageCount> apiResult) {
    if(apiResult!=null&&0<apiResult.getTotalCount()){
      mIvRight1.setImageResource(R.drawable.icon_fw_wdxx);
    }else{
      mIvRight1.setImageResource(R.drawable.icon_fw_xx);
    }
  }

  /**
   * 系统推送消息点击
   */
  @Subscribe(code = RxBusCode.SYSTEM_PUSH_CODE)
  public void systemPush() {
    mTabs.setCurrentTab(2);
    mFragmentManagerUtil.setFragments(2);
    changeTitleAndIcon(2);
    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
      @Override public void run() {
        mTabs.setCurrentTab(2);
      }
    },500);
  }

  @Override public void onResume() {
    super.onResume();
    presenter.queryAppUpdateInfo();
    StatusBarHelper.setStatusBarDarkMode(getActivity());
    RxBus.get().send(RxBusCode.ONRESUME_CODE);
    SPUtils.put(mActivity, SpKeyConstant.HOME_TAB_KEY, "" + mTabs.getCurrentTab());
  }

  @Override protected boolean canDragBack() {
    return false;
  }

  @Override public void onDestroy() {
    super.onDestroy();
    RxBus.get().unRegister(this);
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK) {
      if (requestCode == 888 && null != data) {
        Bundle bundle = data.getExtras();
        if (bundle == null) {
          return;
        }
        if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
          String result = bundle.getString(CodeUtils.RESULT_STRING);
          if (Patterns.WEB_URL.matcher(result).matches() || URLUtil.isValidUrl(result)) {
            //  判断出是URL，打开webview界面
            AgentWebViewActivity.create(this, result, "");
          } else {
            startFragment(SearchUserGroupFragment.create(result));
          }
        } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
          showToast("扫描解析失败,请稍后再试");
        }
      }
    }
  }

  @Override public void onPause() {
    super.onPause();
    SPUtils.put(mActivity, SpKeyConstant.HOME_TAB_KEY, "");
  }

  @Override public void refreshUserInfoSuc(UserInfo userInfo) {
    UserInfo saveUserInfo = MyApplication.getInstance().getUserInfo();
    saveUserInfo.setUserType(userInfo.getUserType());
    UserInfo.refreshInfo(mActivity, saveUserInfo);
    changeTitleAndIcon(mTabs.getCurrentTab());
  }

  @Override public void loginSuccess(LoginEntity loginEntity) {
    MyApplication.getInstance().setToken(loginEntity.getToken());
    MyApplication.getInstance().setUserInfo(loginEntity.getUserInfo());
    SPUtils.put(mActivity, SpKeyConstant.TOKEN_KEY, loginEntity.getToken());
    SPUtils.put(mActivity, SpKeyConstant.USERINFO_KEY,
        new Gson().toJson(loginEntity.getUserInfo()));
  }
}
